import { onBeforeUnmount } from 'vue';
export default function() {
	onBeforeUnmount(() => {
		stop();
	})
	const keySounds = {
		error: '/static/audio/error.mp3', //错误音效
		backspace: '/static/audio/typing-4.mp3', //退格音效
		success: '/static/audio/typing-0.mp3', //正确音效
		bgMusic: '/static/audio/game-bgmusic.mp3', //游戏背景音乐
		explosion: '/static/audio/enemy_down.mp3', //爆炸声音
		shoot: '/static/audio/shoot.mp3' //射击声音
	}
	// 用于存储音频缓冲区
	const audioBuffers = {};
	// 音频上下文
	const audioContext = new(window.AudioContext || window.webkitAudioContext)();
	// 用于存储音频
	let sourceNodes = [];
	/**
	 * 加载音效
	 * @param {Object} url 音效地址
	 */
	async function loadSound(url) {
		const response = await fetch(url);
		const arrayBuffer = await response.arrayBuffer();
		return new Promise((resolve) => {
			audioContext.decodeAudioData(arrayBuffer, (buffer) => {
				resolve(buffer);
			});
		});
	}
	/**
	 * 播放音效
	 * @param {string} type 类型，参考keySounds
	 */
	async function play(type, loop = false) {
		if (keySounds[type]) {
			let buffer = audioBuffers[type];
			if (!buffer) {
				buffer = await loadSound(keySounds[type]);
				audioBuffers[type] = buffer;
			}
			const source = audioContext.createBufferSource();
			source.buffer = buffer;
			source.loop = loop;
			source.connect(audioContext.destination);
			source.start(0);
			sourceNodes.push(source);
		}
	}
	// 停止播放
	function stop() {
		sourceNodes.forEach(item => {
			if (item) {
				item.stop(0);
				item.disconnect();
			}
		})
		sourceNodes = [];
	}
	return {
		play,
		stop
	}
}